#include "httpmgr.h"

#include <QNetworkReply>

HttpMgr::~HttpMgr()
{

}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId reqId, Modules mod)
{
    // 将json数据转字节数组
    QByteArray data = QJsonDocument(json).toJson();
    QNetworkRequest request(url);
    // 设置请求类型
    request.setHeader(QNetworkRequest::ContentTypeHeader,
                      "application/json");
    // 设置内容长度 通过QByteArrayba把data.length从小端转大端
    request.setHeader(QNetworkRequest::ContentLengthHeader,
                      QByteArray::number(data.length()));


    auto self = shared_from_this();

    // 设置回应             // 发送数据
    QNetworkReply * reply = _manager.post(request,data);
    // 处理reply
    connect(reply,&QNetworkReply::finished,
            this,[self,mod,reqId,reply](){
        // 处理错误的情况
        if(reply->error() != QNetworkReply::NoError){
            qDebug() << reply->errorString();
            // 发送信号通知完成 但是失败了
            emit self->SigHttpFinish(reqId,"",ErrorCodes::ERR_NETWORK,mod);
            // 回收reply
            reply->deleteLater();
            return ;
        }
        // 说明没有错误 处理数据
        QString res = reply->readAll();
        qDebug() << res;
        // 发送信号 通知完成
        emit self->SigHttpFinish(reqId,res,ErrorCodes::SUCCESS,mod);
        // 回收 reply
        reply->deleteLater();
        return ;
    });
}

HttpMgr::HttpMgr()
{

    connect(this,&HttpMgr::SigHttpFinish,this,&HttpMgr::SlotHttpFinish);


}

void HttpMgr::SlotHttpFinish(ReqId reqId, QString res, ErrorCodes err, Modules mod)
{
    //  响应对应的操作
    // 注册
    if(mod == Modules::REGISTERMOD){
        emit SigRegModeFinish(reqId,res,err);
    }else if(mod == Modules::RESETMOD){
        emit SigResetModeFinish(reqId,res,err);
    }else if(mod == Modules::LOGINMOD){
        emit SigLoginModeFinish(reqId,res,err);
    }

}



